package com.heima.mongo.mapper;

import com.heima.mongo.pojos.Address;
import com.heima.mongo.pojos.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 操作mapper的方法
 */
@Service
public class PersonMapper {

    @Autowired
    private MongoTemplate mongoTemplate;

    //更新操作
    public void saveMongo(){
        Person person=new Person(1l,"张三222",12,
                new Address("湖北","武汉","黄陂"));
        mongoTemplate.save(person);
    }

    //新增操作
    public void insertMongo(){
        for (int i = 0; i <10 ; i++) {
            Person person=new Person(2l+i,"二狗子"+i,12+i,
                    new Address("湖北","武汉","黄陂"));
            mongoTemplate.insert(person);
        }

    }

    /**
     * delete from 表 where id=2 and name="二狗子"
     */
    public void deleteMongo(){
        Query query=Query.query(
                    Criteria.where("id").is(2l).and("name").is("二狗子")
        );
        mongoTemplate.remove(query,Person.class);
    }

    /**
     * 全查
     */
    public List<Person> queryAll(){
        List<Person> all = mongoTemplate.findAll(Person.class);
        return all;
    }

    /**
     * 单一查询
     */
    public Person queryOne(){
        //根据主键查询，返回值对象
        /*Person person = mongoTemplate.findById(1L, Person.class);
        return person;*/
        Query query=Query.query(Criteria.where("age").is(12));
        Person person = mongoTemplate.findOne(query, Person.class);
        return person;
    }

    /**
     * 根据条件查询
     *
     * select * from 表 where id=1 and age=12
     */
    public List<Person> queryTiaojian(){
        //and条件
       // Query query=Query.query(Criteria.where("id").is(1l).and("age").is(12));

        //or条件  select * from 表 where id=1 or age=20
       // Query query=Query.query(new Criteria().orOperator(Criteria.where("id").is(1l),Criteria.where("age").is(20)));

        //and 和or   select * from 表 where id=1 and (age=12 or name=二狗子)
        Query query=Query.query(Criteria.where("id").is(1l).orOperator(Criteria.where("age").is(20),Criteria.where("name").is("二狗子")));

        List<Person> list = mongoTemplate.find(query, Person.class);
        return list;
    }

    public List<Person> queryLimit(){
        Query query=new Query();
        query.with(Sort.by(Sort.Direction.DESC,"age"));
        List<Person> list = mongoTemplate.find(query, Person.class);
        return list;
    }



}
